<template>
  <div class="page-content">
    <el-row :gutter="20" style="margin-left: 15px">
      <el-button v-auth="'add'" @click="showModel('menu', null, true)" v-ripple>添加菜单</el-button>
      <el-button type="primary" @click="fetchMenuList" :loading="loading">刷新菜单列表</el-button>
    </el-row>

    <div v-if="tableData.length === 0 && !loading" class="empty-data">
      <el-empty description="暂无菜单数据，请点击刷新按钮"></el-empty>
    </div>

    <art-table :data="tableData" v-loading="loading" v-if="tableData.length > 0">
      <template #default>
        <el-table-column label="菜单ID" width="120">
          <template #default="scope">
            <el-tooltip effect="dark" content="菜单ID" placement="top">
              <span class="menu-id">{{ scope.row.id }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="菜单名称">
          <template #default="scope">
            <div>
              <div class="main-menu-title">
                {{ displayMenuTitle(scope.row.meta?.title ? formatMenuTitle(scope.row.meta.title) : (scope.row.name || '未命名菜单')) }}
              </div>
              <!-- 如果有子菜单，显示简要信息 -->
              <div v-if="scope.row.children && scope.row.children.length > 0" class="sub-menu-info">
                <el-tag size="small" type="info">{{ scope.row.children.length }}个子菜单</el-tag>
                <span class="sub-menu-names">
                  {{ getChildMenuNames(scope.row.children) }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由" />

        <el-table-column prop="meta.authList" label="可操作权限">
          <template #default="scope">
            <el-popover
              placement="top-start"
              title="操作"
              :width="200"
              trigger="click"
              v-for="(item, index) in scope.row.meta?.authList || []"
              :key="index"
            >
              <div style="margin: 0; text-align: right">
                <el-button size="small" type="primary" @click="showModel('button', item)"
                  >编辑</el-button
                >
                <el-button size="small" type="danger" @click="deleteAuth(item)">删除</el-button>
              </div>
              <template #reference>
                <el-button class="small-btn">{{ item.title }}</el-button>
              </template>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="created_at" width="180" />
        <el-table-column label="更新时间" prop="updated_at" width="180" />

        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <button-table type="add" v-auth="'add'" @click="showModel('button', null, false, scope.row)" />
            <button-table type="edit" v-auth="'edit'" @click="showDialog('edit', scope.row)" />
            <button-table type="delete" v-auth="'delete'" @click="deleteMenu(scope.row)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="700px" align-center>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="85px">
        <el-form-item label="菜单类型">
          <el-radio-group v-model="labelPosition" :disabled="disableMenuType">
            <el-radio-button value="menu" label="menu">菜单</el-radio-button>
            <el-radio-button value="button" label="button">权限</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <template v-if="labelPosition === 'menu'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="菜单名称" prop="name">
                <el-input v-model="form.name" placeholder="菜单名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="路由地址" prop="path">
                <el-input v-model="form.path" placeholder="路由地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="权限标识" prop="label">
                <el-input v-model="form.label" placeholder="权限标识"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图标" prop="icon">
                <icon-selector :iconType="iconType" :defaultIcon="form.icon" width="229px" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="组件路径" prop="component">
                <el-input v-model="form.component" placeholder="组件路径，例如: /cloudDevice/DeviceManagement"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="父级菜单" prop="parentId">
                <el-select v-model="form.parentId" placeholder="请选择父级菜单" style="width: 100%">
                  <el-option :value="0" label="顶级菜单"></el-option>
                  <template v-for="menu in allMenuOptions" :key="menu.value">
                    <el-option :value="menu.value" :label="menu.label"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="菜单排序" prop="sort" style="width: 100%">
                <el-input-number
                  v-model="form.sort"
                  style="width: 100%"
                  @change="handleChange"
                  :min="0"
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重定向" prop="redirect">
                <el-input
                  v-model="form.redirect"
                  placeholder="重定向地址或外部链接"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="5">
              <el-form-item label="是否启用" prop="isEnable">
                <el-switch v-model="form.isEnable"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="页面缓存" prop="keepAlive">
                <el-switch v-model="form.keepAlive"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="是否显示" prop="isHidden">
                <el-switch v-model="form.isHidden"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="是否内嵌" prop="isIframe">
                <el-switch v-model="form.isIframe"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <template v-if="labelPosition === 'button'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="权限名称" prop="authName">
                <el-input v-model="form.authName" placeholder="权限名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="权限标识" prop="authLabel">
                <el-input v-model="form.authLabel" placeholder="权限标识"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm()" :loading="submitLoading"> 确 定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { useMenuStore } from '@/store/modules/menu'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { IconTypeEnum } from '@/enums/appEnum'
  import { formatMenuTitle } from '@/utils/menu'
  import { onMounted, ref, computed, reactive, nextTick } from 'vue'

  const menuStore = useMenuStore()
  const loading = computed(() => menuStore.getLoading)
  const submitLoading = ref(false)
  
  // 菜单数据
  const tableData = ref<any[]>([])
  // 所有可选的父级菜单选项
  const allMenuOptions = ref<{ value: number; label: string }[]>([])

  // 用于展示更友好的菜单标题
  const displayMenuTitle = (title: string) => {
    if (!title) return '未命名菜单';
    
    // 处理国际化键值
    if (title.startsWith('menus.')) {
      // 提取菜单路径的最后一部分作为可读标题
      const parts = title.split('.');
      if (parts.length > 0) {
        const lastPart = parts[parts.length - 1];
        // 首字母大写
        return lastPart.charAt(0).toUpperCase() + lastPart.slice(1);
      }
    }
    
    return title;
  }

  // 在组件挂载时获取菜单列表
  onMounted(async () => {
    await fetchMenuList()
  })

  // 获取菜单列表
  const fetchMenuList = async () => {
    try {
      console.log('开始获取菜单列表...')
      await menuStore.fetchMenuListForManagement()
      const menuData = menuStore.getMenuTableData
      console.log('获取到的菜单数据:', menuData)
      
      // 确保菜单数据格式正确
      if (Array.isArray(menuData) && menuData.length > 0) {
        // 处理顶级菜单并生成前端ID
        const processMenuItems = (items: any[]) => {
          if (!Array.isArray(items)) return [];
          
          // 主菜单ID从1开始
          return items.map((item, index) => {
            // 复制菜单项
            const menuItem = { ...item };
            
            // 生成主菜单ID：从1开始递增
            const mainMenuId = index + 1;
            // 保存原始ID
            menuItem.originalId = menuItem.id;
            // 设置新的ID
            menuItem.id = mainMenuId;
            
            // 处理必要的字段
            if (!menuItem.meta) {
              menuItem.meta = {
                title: menuItem.name || menuItem.title || '未命名菜单',
                icon: menuItem.icon || ''
              };
            }
            
            if (!menuItem.path && menuItem.url) {
              menuItem.path = menuItem.url;
            }
            
            // 显示格式化后的日期，如果日期不存在则显示"-"
            menuItem.created_at = menuItem.created_at || '-';
            menuItem.updated_at = menuItem.updated_at || '-';
            
            // 如果有子菜单，处理子菜单ID
            if (menuItem.children && Array.isArray(menuItem.children) && menuItem.children.length > 0) {
              menuItem.children = menuItem.children.map((child: any, childIndex: number) => {
                const childItem = { ...child };
                // 保存原始ID
                childItem.originalId = childItem.id;
                // 子菜单ID格式：主菜单ID + 01, 02, 03...
                childItem.id = Number(`${mainMenuId}${String(childIndex + 1).padStart(2, '0')}`);
                
                // 处理子菜单的必要字段
                if (!childItem.meta) {
                  childItem.meta = {
                    title: childItem.name || childItem.title || '未命名子菜单',
                    icon: childItem.icon || ''
                  };
                }
                
                if (!childItem.path && childItem.url) {
                  childItem.path = childItem.url;
                }
                
                // 日期处理
                childItem.created_at = childItem.created_at || '-';
                childItem.updated_at = childItem.updated_at || '-';
                
                return childItem;
              });
            }
            
            return menuItem;
          });
        };
        
        // 处理顶级菜单并设置前端ID
        const topLevelMenus = processMenuItems(menuData);
        tableData.value = topLevelMenus as any[];
        console.log('处理后的菜单数据(含前端ID):', tableData.value);
        
        // 更新父级菜单选项
        updateParentMenuOptions();
      } else {
        tableData.value = [];
        console.warn('获取到的菜单数据为空或格式不正确');
      }
    } catch (error) {
      console.error('获取菜单列表失败:', error);
      tableData.value = [];
    }
  }

  const dialogVisible = ref(false)
  const currentMenuId = ref<number | null>(null)
  const parentMenuId = ref<number | null>(0)
  
  const form = reactive({
    // 菜单
    name: '',
    path: '',
    label: '',
    icon: '',
    component: '',
    parentId: 0,
    isEnable: true,
    sort: 0,
    isMenu: true,
    keepAlive: false,
    isHidden: false,
    redirect: '',
    isIframe: false,
    // 权限
    authName: '',
    authLabel: '',
    authIcon: '',
    authSort: 0
  })
  
  const iconType = ref(IconTypeEnum.UNICODE)

  const labelPosition = ref('menu')
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入菜单名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
    label: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
    component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
    // 权限验证
    authName: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
    authLabel: [{ required: true, message: '请输入权限标识', trigger: 'blur' }]
  })

  const isEdit = ref(false)
  const formRef = ref<FormInstance>()
  const dialogTitle = computed(() => {
    const type = labelPosition.value === 'menu' ? '菜单' : '权限'
    return isEdit.value ? `编辑${type}` : `新建${type}`
  })

  const showDialog = (type: string, row: any) => {
    showModel('menu', row, true)
  }

  const handleChange = () => {}

  const submitForm = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        try {
          // 构造API请求参数
          const params: any = labelPosition.value === 'menu'
            ? {
                meta: {
                  icon: form.icon,
                  keepAlive: form.keepAlive,
                  title: form.name,
                  isEnable: form.isEnable,
                  isMenu: form.isMenu,
                  isHidden: form.isHidden,
                  isIframe: form.isIframe,
                  sort: form.sort
                },
                component: form.component,
                name: form.label,
                parent_id: form.parentId,
                sort: form.sort,
                path: form.path,
                redirect: form.redirect || ''
              }
            : {
                title: form.authName,
                auth_mark: form.authLabel,
                icon: form.authIcon,
                sort: form.authSort
              };

          if (isEdit.value && currentMenuId.value) {
            // 编辑模式 - 添加原始ID
            params.id = currentMenuId.value;
            console.log('提交菜单更新，使用原始ID:', currentMenuId.value);
            await menuStore.updateMenu(params);
          } else {
            // 新增模式
            console.log('提交新增菜单');
            await menuStore.addMenu(params);
          }

          dialogVisible.value = false;
          // 刷新菜单列表
          await fetchMenuList();
        } catch (error) {
          console.error(`${isEdit.value ? '编辑' : '新增'}菜单失败:`, error);
        } finally {
          submitLoading.value = false;
        }
      }
    });
  }

  const showModel = (type: string, row?: any, lock: boolean = false, parentRow?: any) => {
    dialogVisible.value = true
    labelPosition.value = type
    isEdit.value = false
    lockMenuType.value = lock
    currentMenuId.value = null
    
    // 使用原始ID作为父菜单ID
    const parentId = parentRow ? (parentRow.originalId || parentRow.id || 0) : 0
    
    resetForm()
    
    // 设置父菜单ID
    form.parentId = parentId

    if (row) {
      isEdit.value = true
      nextTick(() => {
        // 回显数据
        if (type === 'menu') {
          // 记录菜单原始ID
          currentMenuId.value = row.originalId || row.id || null
          // 菜单数据回显
          form.name = formatMenuTitle(row.meta?.title || '')
          form.path = row.path || ''
          form.label = row.name || ''
          form.icon = row.meta?.icon || ''
          form.component = row.component || ''
          form.parentId = row.parent_id || 0
          form.sort = row.sort || row.meta?.sort || 0
          form.isMenu = row.meta?.isMenu ?? true
          form.keepAlive = row.meta?.keepAlive ?? false
          form.isHidden = row.meta?.isHidden ?? false
          form.isEnable = row.meta?.isEnable ?? true
          form.redirect = row.redirect || ''
          form.isIframe = row.meta?.isIframe ?? false
        } else {
          // 记录权限原始ID
          currentMenuId.value = row.originalId || row.id || null
          // 权限按钮数据回显
          form.authName = row.title || ''
          form.authLabel = row.auth_mark || ''
          form.authIcon = row.icon || ''
          form.authSort = row.sort || 0
        }
      })
    }
  }

  const resetForm = () => {
    formRef.value?.resetFields()
    Object.assign(form, {
      // 菜单
      name: '',
      path: '',
      label: '',
      icon: '',
      component: '',
      parentId: 0,
      sort: 0,
      isMenu: true,
      keepAlive: false,
      isHidden: false,
      redirect: '',
      isIframe: false,
      // 权限
      authName: '',
      authLabel: '',
      authIcon: '',
      authSort: 0
    })
  }

  const deleteMenu = async (row: any) => {
    if (!row) {
      ElMessage.warning('无法删除，菜单数据不完整')
      return
    }
    
    // 使用原始ID进行删除操作
    const originalId = row.originalId || row.id
    if (!originalId) {
      ElMessage.warning('无法删除，缺少菜单ID')
      return
    }

    try {
      await ElMessageBox.confirm('确定要删除该菜单吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await menuStore.deleteMenu([originalId])
      // 重新获取菜单列表
      await fetchMenuList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除菜单失败:', error)
      }
    }
  }

  const deleteAuth = async (item: any) => {
    if (!item) {
      ElMessage.warning('无法删除，权限数据不完整')
      return
    }
    
    // 使用原始ID进行删除操作
    const originalId = item.originalId || item.id
    if (!originalId) {
      ElMessage.warning('无法删除，缺少权限ID')
      return
    }
    
    try {
      await ElMessageBox.confirm('确定要删除该权限吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      await menuStore.deleteMenu([originalId])
      // 重新获取菜单列表
      await fetchMenuList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除权限失败:', error)
      }
    }
  }

  // 修改计算属性，增加锁定控制参数
  const disableMenuType = computed(() => {
    // 编辑权限时锁定为权限类型
    if (isEdit.value && labelPosition.value === 'button') return true
    // 编辑菜单时锁定为菜单类型
    if (isEdit.value && labelPosition.value === 'menu') return true
    // 顶部添加菜单按钮时锁定为菜单类型
    if (!isEdit.value && labelPosition.value === 'menu' && lockMenuType.value) return true
    return false
  })

  // 添加一个控制变量
  const lockMenuType = ref(false)

  // 获取子菜单名称
  const getChildMenuNames = (children: any[]) => {
    if (!Array.isArray(children) || children.length === 0) return '';
    
    // 获取子菜单的名称，优先使用meta.title，其次使用name
    return children
      .map(child => {
        // 优先使用格式化后的标题
        if (child.meta?.title) {
          return displayMenuTitle(formatMenuTitle(child.meta.title));
        }
        // 其次使用name
        return child.name || '未命名菜单';
      })
      .join('、');
  }

  // 更新父级菜单选项
  const updateParentMenuOptions = () => {
    const options: { value: number; label: string }[] = [];
    
    // 处理所有菜单项，包括子菜单
    const processMenuForOptions = (menus: any[], prefix = '') => {
      if (!Array.isArray(menus)) return;
      
      menus.forEach(menu => {
        // 使用原始ID作为选项值
        const originalId = menu.originalId || menu.id;
        if (originalId) {
          const title = formatMenuTitle(menu.meta?.title || menu.name || '未命名菜单');
          const label = prefix ? `${prefix} / ${title}` : title;
          
          options.push({
            value: originalId,
            label: label
          });
        }
        
        // 递归处理子菜单
        if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
          const newPrefix = prefix ? `${prefix} / ${formatMenuTitle(menu.meta?.title || menu.name)}` : formatMenuTitle(menu.meta?.title || menu.name);
          processMenuForOptions(menu.children, newPrefix);
        }
      });
    };
    
    processMenuForOptions(tableData.value);
    allMenuOptions.value = options;
  }
</script>

<style lang="scss" scoped>
  .page-content {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }

    :deep(.small-btn) {
      height: 30px !important;
      padding: 0 10px !important;
      font-size: 12px !important;
    }
    
    .menu-id {
      font-family: 'Courier New', monospace;
      font-weight: bold;
      color: #409EFF;
      background-color: #ecf5ff;
      padding: 2px 8px;
      border-radius: 4px;
      border: 1px solid #d9ecff;
      cursor: default;
    }
    
    .main-menu-title {
      font-weight: bold;
      margin-bottom: 5px;
    }
    
    .sub-menu-info {
      margin-top: 5px;
      font-size: 12px;
      color: #666;
      display: flex;
      align-items: center;
      
      .el-tag {
        margin-right: 8px;
      }
      
      .sub-menu-names {
        color: #999;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 200px;
      }
    }
  }
</style>

